package com.zengchen.content.config.ribbonrule;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosDiscoveryProperties;
import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer;

/**
 * <p>
 *  权重负载规则
 * </p>
 *
 * @author zengchen
 * @since 2019-08-11
 */
@Slf4j
public class NacosWeightedRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties discoveryProperties;

    private Server choose(DynamicServerListLoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        }
        String name = lb.getName();
        try {
            Instance instance = discoveryProperties.namingServiceInstance()
                    .selectOneHealthyInstance(name);
            return new NacosServer(instance);
        } catch (NacosException e) {
            log.error("权重规则发生异常",e);
        }
        return null;
    }

    @Override
    public Server choose(Object key) {
        log.info("负载均衡规则：NacosWeightedRule");
        return choose((DynamicServerListLoadBalancer) getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }
}
